package com.zego.wawaji.ui.Fragment.play;

import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.BounceInterpolator;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.noble.library.observer.MsgMgr;
import com.noble.library.observer.PObserver;
import com.noble.library.time.TimeUtil;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.Transformer;
import com.youth.banner.loader.ImageLoader;
import com.zego.wawaji.R;
import com.zego.wawaji.base.module.ModuleMgr;
import com.zego.wawaji.base.observer.MsgType;
import com.zego.wawaji.base.toast.PToast;
import com.zego.wawaji.http.request.HttpResponse;
import com.zego.wawaji.http.request.RequestComplete;
import com.zego.wawaji.http.request.UrlParam;
import com.zego.wawaji.socket.utils.AnimatorUtil;
import com.zego.wawaji.third.zego.ZegoMgr;
import com.zego.wawaji.ui.Fragment.BaseFragment;
import com.zego.wawaji.ui.UIShow;
import com.zego.wawaji.ui.adapter.RoomListAdapter;
import com.zego.wawaji.ui.bean.banner.NoticeList;
import com.zego.wawaji.ui.bean.user.UserDetail;
import com.zego.wawaji.ui.bean.wawa.RoomStatus;
import com.zego.wawaji.ui.bean.wawa.WawaJi;
import com.zego.wawaji.ui.bean.wawa.WawaJiList;
import com.zego.wawaji.ui.dialog.PickerDialogUtil;
import com.zego.wawaji.ui.view.adDialog.bean.AdInfo;
import com.zego.wawaji.ui.view.adDialog.bean.AdInfoList;
import com.zego.wawaji.wawaji_client.AppTinkerLike;

import java.util.List;

/**
 * 游戏页
 * Created by Su on 2018/1/18.
 */
public class PlayFragment extends BaseFragment implements View.OnClickListener, RequestComplete, PObserver {
    private List<WawaJi> mRoomList = null;
    private WawaJiList wawaJiList;
    private RecyclerView mRecyclerView = null;
    private RoomListAdapter adapter;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        setContentView(R.layout.play_fragment);
        initTitle();
        initViews();
        initZegoSDK();
        return getContentView();
    }

    // 还未成功初始化时初始化SDK
    private void initZegoSDK() {
        if (!ZegoMgr.isInitSuc) {
            ModuleMgr.getCenterMgr().reqMyInfo(response -> {
                if (!response.isCache() && response.isOk()) {
                    if (!ZegoMgr.isInitSuc)
                        ZegoMgr.getInstance().initSDK();
                }
            });
        }
    }

    private void reqData() {
        ModuleMgr.getWawaMgr().reqWawajiList(this);
        ModuleMgr.getWawaMgr().reqBannerNotice(this);
    }

    private void initTitle() {
        setTitle("首页");
        setTitleRightImg(R.drawable.play_fragment_right_title, v -> PickerDialogUtil.showPayDialog(getActivity()));
        setTitleLeftImg(R.drawable.gift_bag_img, v -> PickerDialogUtil.showEveryGiftBagDialog(getActivity()));
    }

    private void initViews() {
        try {
            MsgMgr.getInstance().attach(this);
            mRecyclerView = (RecyclerView) findViewById(R.id.recyclerview);
            mRecyclerView.setLayoutManager(new GridLayoutManager(getActivity(), 2));

            adapter = new RoomListAdapter(getActivity(), mRoomList);
            mRecyclerView.setAdapter(adapter);

            adapter.setItemClickListener((view, position) -> {
                try {
                    UIShow.showPlayActivity(getActivity(), mRoomList.get(position));
                } catch (Exception e) {
                    PToast.showShort("房间列表异常，请刷新重试");
                }
            });
            reqData();
            initFloatWindow();
            initAdFloat();
        } catch (Exception e) {
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_float:
                UIShow.showPayAwardAct(getActivity());
                break;
        }
    }

    @Override
    public void onRequestComplete(HttpResponse response) {
        if (response.getUrlParam() == UrlParam.reqWawajiList) {
            if (!response.isOk()) return;

            wawaJiList = (WawaJiList) response.getBaseData();
            mRoomList = wawaJiList.getWawaJiShowList();
            adapter.setList(mRoomList);
        }

        // 轮播banner
        if (response.getUrlParam() == UrlParam.reqBannerNotice) {
            if (!response.isOk()) return;

            initBanner((NoticeList) response.getBaseData());
        }
    }

    /**
     * 初始化轮播图
     */
    private void initBanner(NoticeList noticeList) {
        if (noticeList == null) return;
        List<String> images = noticeList.getNoticeImg();
        final List<String> links = noticeList.getNoticeLink();

        Banner banner = (Banner) findViewById(R.id.banner);
        banner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR)
                .setImages(images)
                .setBannerAnimation(Transformer.ZoomOutSlide)
                .setDelayTime(4000)
                .setIndicatorGravity(BannerConfig.RIGHT)
                .setImageLoader(new ImageLoader() {
                    @Override
                    public void displayImage(Context context, Object path, ImageView imageView) {
                        com.zego.wawaji.third.image.ImageLoader.loadRoundCenterCrop(AppTinkerLike.getContext(), path, imageView);
                    }
                })
                .setOnBannerListener(position -> ModuleMgr.getWawaMgr().skipLogic(getActivity(), links.get(position))).start();
    }

    public void changeRoomStatus(String content) {
        RoomStatus roomStatus = new RoomStatus();
        roomStatus.parseJson(content);

        if (mRoomList == null) return; // 还未拿到房间列表

        boolean inList = false;
        // 更新现有娃娃机
        for (int i = 0; i < mRoomList.size(); i++) {
            if (roomStatus.getRid() == mRoomList.get(i).getId()) {
                inList = true;
                if (roomStatus.getWwjStatus() == -3) {  // 该娃娃机需要隐藏
                    mRoomList.remove(i);
                    adapter.notifyItemRemoved(i);
                } else {
                    mRoomList.get(i).setStatus(roomStatus.getWwjStatus());
                    adapter.notifyItemChanged(i);
                }
                break;
            }
        }

        // 更新不在列表中的娃娃机
        if (!inList) {
            if (wawaJiList == null) return;
            List<WawaJi> roomListAll = wawaJiList.getWawaJiList();

            for (int j = 0; j < roomListAll.size(); j++) {
                if (roomStatus.getRid() == roomListAll.get(j).getId()) {
                    if (roomStatus.getWwjStatus() != -3) {
                        roomListAll.get(j).setStatus(roomStatus.getWwjStatus());
                        mRoomList.add(roomListAll.get(j));
                        adapter.notifyItemInserted(mRoomList.size() - 1);
                    }
                    break;
                }
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        MsgMgr.getInstance().detach(this);
    }

    @Override
    public void onMessage(String key, Object value) {
        switch (key) {
            case MsgType.MT_Msg_RoomChange:
                changeRoomStatus((String) value);
                break;

            case MsgType.MT_Net_Reconnet:
                initZegoSDK();
                break;
        }
    }


    // ===================================== 广告提示浮窗 ==============================
    private ImageView adFloat;
    private LinearLayout adLayout;
    private TextView ad_text;

    private void initAdFloat() {
        adLayout = (LinearLayout) findViewById(R.id.ad_layout);
        AdInfoList adInfoList = ModuleMgr.getWawaMgr().getAdInfoList();
        if (adInfoList == null || adInfoList.getAdInfoList().size() <= 0) {
            adLayout.setVisibility(View.GONE);
            return;
        }

        adFloat = (ImageView) findViewById(R.id.ad_float);
        ad_text = (TextView) findViewById(R.id.ad_text);
        ad_text.setVisibility(isShow() ? View.GONE : View.VISIBLE);

        RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(adLayout.getLayoutParams());
        lp.rightMargin = 20;
        lp.bottomMargin = isShow() ? 200 : 20;
        lp.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
        lp.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
        adLayout.setLayoutParams(lp);
        AdInfo info = adInfoList.getAdInfoList().get(0);
        com.zego.wawaji.third.image.ImageLoader.loadCenterCrop(getContext(), info.getImgSmall(), adFloat);

        adFloat.setOnClickListener(v -> ModuleMgr.getWawaMgr().skipLogic(getActivity(), info.getUrl()));
    }

    // ===================================== 首冲提示浮窗 ==============================
    private TextView fv_text;
    private LinearLayout ll_fall_view;
    private ImageView btn_float;
    private ObjectAnimator animator;
    private TranslateAnimation translateAnimation;
    int height;

    private void initFloatWindow() {
        fv_text = (TextView) findViewById(R.id.fv_text);
        btn_float = (ImageView) findViewById(R.id.btn_float);
        ll_fall_view = (LinearLayout) findViewById(R.id.ll_fall_view);
        if (!isShow()) {
            fv_text.setVisibility(View.GONE);
            ll_fall_view.setVisibility(View.GONE);
            return;
        }
        btn_float.setOnClickListener(this);
        ll_fall_view.post(() -> {
            height = ll_fall_view.getMeasuredHeight() - btn_float.getMeasuredHeight();
            initTranslate();
            translateAnimation.setAnimationListener(new Animation.AnimationListener() {
                @Override
                public void onAnimationStart(Animation animation) {
                }

                @Override
                public void onAnimationEnd(Animation animation) {
                    btn_float.clearAnimation();
                    btn_float.setY(height);
                    animator = AnimatorUtil.tada(btn_float);
                    animator.setRepeatCount(ValueAnimator.INFINITE);
                    animator.start();
                }

                @Override
                public void onAnimationRepeat(Animation animation) {
                }
            });
        });
    }

    private void initTranslate() {
        translateAnimation = new TranslateAnimation(0, 0, 0, height);
        translateAnimation.setInterpolator(new BounceInterpolator());
        translateAnimation.setDuration(800);
        translateAnimation.setFillAfter(true);
        btn_float.setAnimation(translateAnimation);
    }

    private boolean isShow() {
        UserDetail userDetail = ModuleMgr.getCenterMgr().getMyInfo();
        if (TimeUtil.rfcNull(userDetail.getFirstRechargeTime())) {  // 用户未首充
            return true;
        }

        long days = TimeUtil.getIntervalDays(TimeUtil.rfcDateTime(userDetail.getFirstRechargeTime())
                , ModuleMgr.getAppMgr().getTime());
        return days <= 8;
    }
}
